package com.hmall.order.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description UserInterceptor
 * @Author zhengyuan&junjun
 * @Date 2024-11-15
 */


@Component
public class UserInterceptor implements HandlerInterceptor {
  private   static  final  ThreadLocal<String> userTheaLocal = new ThreadLocal<>();  //用来存放用户信息

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.判断是否为动态方法，如果不是直接放行
        if (!(handler instanceof HandlerMethod)){
            return  true;

        }

        //2.定义权限
        String authorization = request.getHeader("authorization");
        if (authorization != null){
           userTheaLocal.set(authorization);    //存入用户id
        }
         return  true;

    }
    //3.获取用户id
    public  static String getuserbyid(){
        return  userTheaLocal.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
